package com.atguigu.tingshu.live.config;/*
 * title:
 * author:
 * date:
 * description:
 * */

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.model.live.SocketMsg;
import jakarta.websocket.Session;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChatRoomContainer {
    private static Map<Long, List<Long>> userMap = new ConcurrentHashMap<>();
    private static Map<Long, Session> sessionMap = new ConcurrentHashMap<>();

    public static void addUser(Long roomId, Long userId, Session session) {
        List<Long> userIdList = userMap.get(roomId);
        if (userIdList == null) {
            userIdList = new ArrayList<>();
            userMap.put(roomId, userIdList);
        }
        userIdList.add(userId);
        sessionMap.put(userId, session);
    }

    public static void removeUser(Long roomId, Long userId) {
        List<Long> userIdList = userMap.get(roomId);
        userIdList.remove(userId);
        sessionMap.remove(userId);
    }

    public static List<Long> getUser(Long roomId) {
        List<Long> userIdList = userMap.get(roomId);
        return userIdList;
    }

    public static Integer getUserCount(Long roomId) {
        List<Long> userIdList = userMap.get(roomId);
        if (userIdList == null) {
            return 0;
        }
        return userIdList.size();
    }

    public static void sendMsg(String msg) {
        if (StringUtils.isBlank(msg)) {
            return;
        }
        SocketMsg socketMsg = JSON.parseObject(msg, SocketMsg.class);
        if (socketMsg == null || socketMsg.getMsgType().equals(SocketMsg.MsgTypeEnum.HEART_BEAT.getCode())) {
            return;
        }
        Long liveRoomId = socketMsg.getLiveRoomId();
        List<Long> userIdList = userMap.get(liveRoomId);
        if (userIdList == null) {
            return;
        }
        userIdList.forEach(userId -> {
                    Session session = sessionMap.get(userId);
                    if (session != null) {
                        session.getAsyncRemote().sendText(JSON.toJSONString(socketMsg));
                    }
                }
        );
    }
}
